﻿<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--[if lt IE 9]>
<script type="text/javascript" src="lib/html5shiv.js"></script>
<script type="text/javascript" src="lib/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="static/h-ui/css/H-ui.min.css" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/H-ui.admin.css" />
<link rel="stylesheet" type="text/css" href="lib/Hui-iconfont/1.0.8/iconfont.css" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/skin/default/skin.css" id="skin" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/style.css" />
<!--[if IE 6]>
<script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js" ></script>
<script>DD_belatedPNG.fix('*');</script>
<![endif]-->
<title>建材列表</title>
<link rel="stylesheet" href="lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" type="text/css">
<style>
	tr>td:nth-of-type(2){
		padding: 0;
	}
</style>
</head>
<body class="pos-r">
<div class="pos-a" style="width:200px;left:0;top:0; bottom:0; height:100%; border-right:1px solid #e5e5e5; background-color:#f5f5f5; overflow:auto;">
	<ul id="treeDemo" class="ztree"></ul>
</div>
<div style="margin-left:200px;">
	<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 产品管理 <span class="c-gray en">&gt;</span> 产品列表 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a></nav>
	<div class="page-container">
		<div class="cl pd-5 bg-1 bk-gray mt-20"> 
			<span class="l">
				<a href="javascript:;" onclick="product_del()" class="btn btn-danger radius"><i class="Hui-iconfont">&#xe6e2;</i> 批量删除</a> 
				<a class="btn btn-primary radius" onclick="product_add('添加产品','product-add.html')" href="javascript:;"><i class="Hui-iconfont">&#xe600;</i> 添加产品</a>
				<a class="btn btn-primary radius" onclick="show_category();" href="javascript:;"><i class="Hui-iconfont">&#xe6df;</i> 更改分类</a>
				<a class="btn btn-primary radius" onclick="showNewerModal();" href="javascript:;"><i class="Hui-iconfont">&#xe6df;</i> 更改新品</a>
			</span> 
			<button name="" id="searchProduct" class="btn btn-success r" type="submit"><i class="Hui-iconfont">&#xe665;</i> 搜产品</button>
			<input type="text" name="productname" id="" placeholder=" 产品名称" style="width:250px" class="input-text r">
		</div>
		<div class="mt-20">
			<table id="brandTable" class="table table-border table-bordered table-bg table-hover">
				<thead>
					<tr class="text-c">
						<th><input name="" type="checkbox" value=""></th>
						<th>图片</th>
						<th>产品名称</th>
						<th>描述</th>
						<th>分类</th>
						<th>品牌</th>
						<th>渠道</th>
						<th>规格价格</th>
						<th>新品</th>
						<th>发布状态</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
		</div>
	</div>
</div>
<div id="editCategory" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content radius">
			<div class="modal-header">
				<h3 id="operateRemind" class="modal-title" style="text-align: center;">更改分类</h3>
				<a class="close" data-dismiss="modal" aria-hidden="true" href="javascript:void();">×</a>
			</div>
			<div class="modal-body">
				<table>
					<tr>
						<td width="100">选择分类：</td>
						<td>
							<!-- <input name="categoryid" type="hidden"> -->
							<select name="category" class="select">
								<option value="0">一级分类</option>
							</select>
						</td>
					</tr>
				</table>
			</div>
			<div class="modal-footer">
				<button class="btn btn-primary" onclick="category_change();">确定</button>
				<button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>
			</div>
		</div>
	</div>
</div>
<div id="editNewer" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content radius">
			<div class="modal-header">
				<h3 id="operateRemind" class="modal-title" style="text-align: center;">更改新品</h3>
				<a class="close" data-dismiss="modal" aria-hidden="true" href="javascript:void();">×</a>
			</div>
			<div class="modal-body">
				<table>
					<tr>
						<td width="100">更改新品状态：</td>
						<td>
							<div style="padding: 10px 0;" class="formControls col-xs-8 col-sm-9 skin-minimal">
								<div class="radio-box">
									<input name="isNewer" value="1" type="radio" id="sex-1" checked>
									<label for="sex-1">是</label>
								</div>
								<div class="radio-box">
									<input type="radio" id="sex-2" value="0" name="isNewer">
									<label for="sex-2">否</label>
								</div>
							</div>
						</td>
					</tr>
				</table>
			</div>
			<div class="modal-footer">
				<button class="btn btn-primary" onclick="newer_change();">确定</button>
				<button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>
			</div>
		</div>
	</div>
</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript" src="lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="static/h-ui/js/H-ui.min.js"></script> 
<script type="text/javascript" src="static/h-ui.admin/js/H-ui.admin.js"></script> <!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="lib/My97DatePicker/4.8/WdatePicker.js"></script> 
<script type="text/javascript" src="lib/datatables/1.10.0/jquery.dataTables.min.js"></script> 
<script type="text/javascript" src="lib/laypage/1.2/laypage.js"></script>
<script type="text/javascript">
var searchname='',searchCategoryIds=[]
function getChildnodesId(node) {
	var nodeId=[]
	nodeId.push(node.id)
	if (node.children) {
		node.children.map(function(elem,index) {
			nodeId=nodeId.concat(getChildnodesId(elem))
		})
	}
	return nodeId;
}
var setting = {
	view: {
		dblClickExpand: false,
		showLine: false,
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable:true,
			idKey: "id",
			pIdKey: "pId",
			rootPId: ""
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("tree");
			if (treeNode.isParent) {
				searchCategoryIds=getChildnodesId(treeNode);
			} else {
				searchCategoryIds=[treeNode.id];
			}
			getDataByConditions()
			return true;
		}
	}
};
var zNodes =[
	{ id:0, pId:null, name:"所有分类", open:true}
];
var other;
$.ajax({
	url: '/admin/category/get',
	async: false,
	success:function(data) {
		if (0==data.code) {
			data.data.map(function(elem,index) {
				var tmp={}
				tmp.id=elem.id
				tmp.pId=elem.pid
				tmp.name=elem.categoryname
				tmp.isParent=elem.isParent
				if ('其它'==tmp.name) {
					other=tmp
				} else {
					zNodes.push(tmp)
				}
				
			})
		}
	}
});
if (other) {
	zNodes.push(other)
}	
$(document).ready(function(){
	var t = $("#treeDemo");
	t = $.fn.zTree.init(t, setting, zNodes);
	//demoIframe = $("#testIframe");
	//demoIframe.on("load", loadReady);
	var zTree = $.fn.zTree.getZTreeObj("tree");
	//zTree.selectNode(zTree.getNodeByParam("id",'11'));
});


/*产品-添加*/
function product_add(title,url){
	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
}
/*产品-查看*/
function product_show(title,url,id){
	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
}
/*产品-审核*/
function product_shenhe(obj,id){
	layer.confirm('审核文章？', {
		btn: ['通过','不通过'], 
		shade: false
	},
	function(){
		$(obj).parents("tr").find(".td-manage").prepend('<a class="c-primary" onClick="product_start(this,id)" href="javascript:;" title="申请上线">申请上线</a>');
		$(obj).parents("tr").find(".td-status").html('<span class="label label-success radius">已发布</span>');
		$(obj).remove();
		layer.msg('已发布', {icon:6,time:1000});
	},
	function(){
		$(obj).parents("tr").find(".td-manage").prepend('<a class="c-primary" onClick="product_shenqing(this,id)" href="javascript:;" title="申请上线">申请上线</a>');
		$(obj).parents("tr").find(".td-status").html('<span class="label label-danger radius">未通过</span>');
		$(obj).remove();
    	layer.msg('未通过', {icon:5,time:1000});
	});	
}
/*产品-下架*/
function product_stop(obj,id){
	layer.confirm('确认要下架吗？',function(index){
		$(obj).parents("tr").find(".td-manage").prepend('<a style="text-decoration:none" onClick="product_start(this,\''+id+'\')" href="javascript:;" title="发布"><i class="Hui-iconfont">&#xe603;</i></a>');
		$(obj).parents("tr").find(".td-status").html('<span class="label label-defaunt radius">已下架</span>');
		$(obj).remove();
		changeShelfStatus(id,false)
	});
}
/*产品-发布*/
function product_start(obj,id){
	layer.confirm('确认要发布吗？',function(index){
		$(obj).parents("tr").find(".td-manage").prepend('<a style="text-decoration:none" onClick="product_stop(this,\''+id+'\')" href="javascript:;" title="下架"><i class="Hui-iconfont">&#xe6de;</i></a>');
		$(obj).parents("tr").find(".td-status").html('<span class="label label-success radius">已发布</span>');
		$(obj).remove();
		changeShelfStatus(id,true)
	});
}
function changeShelfStatus(id,status) {//更改上下架状态
	$.post('/admin/product/edit', {
		_id: id,
		shelfStatus: status,
	}, function(data, textStatus, xhr) {
		console.log(data);
		if (0==data.code) {
			if (status) {
				layer.msg('已发布!',{icon: 6,time:1000});
			} else {
				layer.msg('已下架!',{icon: 5,time:1000});
			}
		} else {
			layer.msg('更新数据失败，请稍后再试!',{icon: 5,time:1000});
		}
			
	});
}
function showNewerModal() {
	$('#editNewer').modal('show')
}
/*产品-更改分类*/
function show_category() {
	$.ajax({
		url: '/admin/category/get?isParent=false',
		success:function(data) {
			if (0==data.code) {
				var data=data.data
				var tmpStr='',htmlStr=''
				data.map(function(elem,index) {
					if ('其它'==elem.categoryname) {
						tmpStr='<option value="'+elem._id+'">其它</option>'
					} else {
						htmlStr+='<option value="'+elem._id+'">'+elem.categoryname+'</option>'
					}
				})
				htmlStr+=tmpStr
				$('select[name="category"]').html(htmlStr)
			}
			$('#editCategory').modal('show')
		}
	});
}
function newer_change(){
	var editProductId=[];
	$('td>input:checked').map(function(index, elem) {
		editProductId.push($(elem).attr('data-id'))
	})
	$.post('/admin/product/changeNewer', {
		_ids: editProductId,
		isNewer:$('input[name="isNewer"]:checked').val(),
	}, function(data, textStatus, xhr) {
		console.log(data);
		$('#editNewer').modal('hide')
		layer.msg(data.message,{icon:1,time:1000});
		if (0==data.code) {
			setTimeout(()=>{
				window.location.reload()
			},1000);
		}
	});
}
function category_change(){
	var editProductId=[];
	$('td>input:checked').map(function(index, elem) {
		editProductId.push($(elem).attr('data-id'))
	})
	$.post('/admin/product/changeCategory', {
		_ids: editProductId,
		category:$('select[name="category"]').val()
	}, function(data, textStatus, xhr) {
		console.log(data);
		$('#editCategory').modal('hide')
		layer.msg(data.message,{icon:1,time:1000});
		if (0==data.code) {
			setTimeout(()=>{
				window.location.reload()
			},1000);
		}
	});
}
/*产品-删除*/
function product_del(obj,id){
	var delProductId=[];
	if (id) {
		delProductId.push(id);
		var remindStr='确认要删除吗？'
	} else {
		$('td>input:checked').map(function(index, elem) {
			delProductId.push($(elem).attr('data-id'))
		})
		var remindStr='你确定要删除选中的产品吗？'
	}
	layer.confirm(remindStr,function(index){
		$.post('/admin/product/del', {
			_id: delProductId
		}, function(data, textStatus, xhr) {
			console.log(data);
			if (0==data.code) {
				if (id) {
					$(obj).parents("tr").remove();
					layer.msg('已删除!',{icon:1,time:1000});
				} else {
					window.location.reload()
				}
			} else {
				layer.msg('更新数据失败，请稍后再试!',{icon: 5,time:1000});
			}
		});
	});
}

/*产品-申请上线*/
function product_shenqing(obj,id){
	$(obj).parents("tr").find(".td-status").html('<span class="label label-default radius">待审核</span>');
	$(obj).parents("tr").find(".td-manage").html("");
	layer.msg('已提交申请，耐心等待审核!', {icon: 1,time:2000});
}

/*产品-编辑*/
function product_edit(title,url,id){
	var index = layer.open({
		type: 2,
		title: title,
		content: url+'?_id='+id
	});
	layer.full(index);
}

var currentPage=1;

$.dataTablesSettings = {
    "aLengthMenu": [10, 25, 50, 100],
    "bAutoWidth": false,
    "bDeferRender": true,
    "bLengthChange": true,
    "sAjaxSource": "/admin/product/getlist",
    "fnServerData" : function(sSource, aDataSet, fnCallback) {    
        $.ajax({    
            "dataType" : 'json',    
            "type" : "POST",    
            "url" : sSource,    
            "data" : aDataSet,    
            "success" : function(data) {
            	currentPage=data.currentPage
            	fnCallback(data)
            }    
        });    
    },
    "bPaginate": true,
    "bServerSide": true,
	"bStateSave": true,//状态保存
    "iDisplayLength": 10,
    searching: false,//是否显示搜索框
    bSort: false,//是否显示搜索框
    // info: false,//是否显示页码详细信息
    "bFilter": true,
    "aoColumnDefs": [
    	{
	        "data": "NULL",
	        "render": function(data, type, row, meta) {
	            return '<input name="" type="checkbox" value="" data-id="'+row._id+'">';
	        },
	        "targets": 0
	    },
	    {
	        "data": "NULL",
	        "render": function(data, type, row, meta) {
	            return '<img style="min-height:100px;max-height:100px;" src="'+row.picture+'">';
	        },
	        "targets":1
	    },
	    {
	        "data": "productname",
	        "targets":2
	    },
	    {
	        "data": "desc",
	        "targets":3
	    },
	    {
	        "data": "category",
	        "targets":4
	    },
	    {
	        "data": "brand",
	        "targets":5
	    },
	    {
	        "data": "channel",
	        "targets":6
	    },
	    {
	        "data": "species",
	        "targets":7
	    },
	    {
	        "data": "NULL",
	        "className":'td-newer',
	        "render": function(data, type, row, meta) {
	        	if (row.newer&&parseInt(row.newer)) {
	        		return '是';
	        	} else {
	        		return '否'
	        	}
	        },
	        "targets":8
	    },
	    {
	        "data": "NULL",
	        "className":'td-status',
	        "render": function(data, type, row, meta) {
	        	if (row.shelf) {
	        		return '<span class="label label-success radius">已发布</span>';
	        	} else {
	        		return '<span class="label label-defaunt radius">已下架</span>'
	        	}
	            
	        },
	        "targets":9
	    },
	    {
	        "data": "NULL",
	        "className":'td-manage',
	        "render": function(data, type, row, meta) {
	        	if (row.shelf) {
	        		var str='<a style="text-decoration:none" onClick="product_stop(this,\''+row._id+'\')" href="javascript:;" title="下架"> <i class="Hui-iconfont">&#xe6de;</i> </a>'
	        	} else {
	        		var str='<a style="text-decoration:none" onClick="product_start(this,\''+row._id+'\')" href="javascript:;" title="发布"><i class="Hui-iconfont">&#xe603;</i></a>'
	        	}
	            return str+' <a style="text-decoration:none" class="ml-5" onClick="product_edit(\'产品编辑\',\'product-add.html\',\''+row._id+'\')" href="javascript:;" title="编辑"> <i class="Hui-iconfont">&#xe6df;</i> </a> <a style="text-decoration:none" class="ml-5" onClick="product_del(this,\''+row._id+'\')" href="javascript:;" title="删除"> <i class="Hui-iconfont">&#xe6e2;</i> </a>';
	        },
	        "targets": 10
    }],
    "fnServerParams": function (aoData) {
        aoData._rand = Math.random();
    },
    "fnDrawCallback": function () {

    }

}
dataTable = $("#brandTable").dataTable($.dataTablesSettings);

$('#searchProduct').click(function () {
	searchname=$('input[name="productname"]').val()
	getDataByConditions()
});

//根据搜索和分类获取数据
function getDataByConditions(curPage) {
	//searchCategoryIds
    //这里重新设置参数
    $.dataTablesSettings.fnServerParams = function (aoData) {
        aoData._rand = Math.random();
        aoData.push(
            { "name": "productname", "value": searchname },
            { "name": "categoryIds", "value": searchCategoryIds }
        );
    }
    //搜索就是设置参数，然后销毁datatable重新再建一个
    dataTable.fnDestroy(false);
    dataTable = $("#brandTable").dataTable($.dataTablesSettings);    
	dataTable.fnPageChange(0);//当前页刷新
}


// 子页面关闭时，父页面刷新
window.addEventListener('message',handleMessage,false);
function handleMessage(e) {
	if ('reload'==e.data) {
		dataTable.fnPageChange(currentPage-1);//当前页刷新
	}
}
$('.skin-minimal input').iCheck({
	checkboxClass: 'icheckbox-blue',
	radioClass: 'iradio-blue',
	increaseArea: '20%'
});
</script>
</body>
</html>
